//
//  PaperListView.m
//  MobileStudy
//
//  Created by hongbao.cui on 13-6-4.
//  Copyright (c) 2013年 hongbao.cui. All rights reserved.
//

#import "PaperListView.h"
#import <QuartzCore/QuartzCore.h>
#import "SingleSelected_UIButton.h"
#import "XingAndLabel_UIView.h"
#import "ISMutileButton.h"
#import <QuartzCore/QuartzCore.h>
#import "ApplicationUtils.h"
@implementation PaperListView
@synthesize paperDelegate;
@synthesize paperDict;
@synthesize selectedBtn;
static NSMutableDictionary  *dataDict = nil;
+(void)setDataDict:(NSMutableDictionary *)_dataDict{
    if (dataDict!=_dataDict) {
        dataDict = _dataDict;
    }
}
+(NSMutableDictionary *)getDataDict{
    return dataDict;
}
-(void)selectBtnClicked:(ISMutileButton *)sender{//选择按钮
    if (sender.isMultile) {
        [self.selectedBtn setSelected:NO];
        UIButton *selectButton = (UIButton *)[sender.superview viewWithTag:88];
        [selectButton setSelected:YES];
        self.selectedBtn = selectButton;
    }else{
        if (sender.selected) {
            [sender setSelected:NO];
        }else{
            [sender setSelected:YES];
        }
    }
    if (paperDelegate!=nil&&[paperDelegate respondsToSelector:@selector(selectBtnClicked:)]) {
        [paperDelegate selectBtnClicked:sender];
    }
}
-(void)choseBtnClicked:(ISMutileButton *)sender{//选择按钮
    if (sender.isMultile) {
        [self.selectedBtn setSelected:NO];
        UIButton *selectButton = (UIButton *)[sender.superview viewWithTag:88];
        [selectButton setSelected:YES];
        self.selectedBtn = selectButton;
    }else{
        UIButton *selectButton = (UIButton *)[sender.superview viewWithTag:88];
        if (selectButton.selected) {
            [selectButton setSelected:NO];
        }else{
            [selectButton setSelected:YES];
        }
    }
    if (paperDelegate!=nil&&[paperDelegate respondsToSelector:@selector(selectBtnClicked:)]) {
        [paperDelegate selectBtnClicked:sender];
    }
//    NSString *orderIdStr =[dataDict objectForKey:@"orderid"];
//    NSString *titleStr =[dataDict objectForKey:@"questionContent"];
//    NSString *str = [NSString stringWithFormat:@"%@、%@",orderIdStr,titleStr];
//    CGSize size_0 = CGSizeMake(300, 1000);
//    CGSize size = [str sizeWithFont:[UIFont systemFontOfSize:16.0]constrainedToSize:size_0 lineBreakMode:UILineBreakModeCharacterWrap];
//    int h = size.height+30;
//    NSArray  *optionsArray = [dataDict objectForKey:@"options"];
//    XingAndLabel_UIView  *titleLableView = (XingAndLabel_UIView *)sender.superview;
//    NSString *optionsStr =titleLableView.titleLabel.text;
//    NSString *selectionStr = [[optionsStr componentsSeparatedByString:@"."] objectAtIndex:0];
//    
//    FMSCHBLog(@"optionsStr:%@",optionsStr);
//    if (selectionStr==nil) {
//        selectionStr = @"您没有选择答案";
//    }else{
//        
//    }
//    NSString *anyliseHTMLData = [NSString stringWithFormat:@"<p><a><font color=\"#0000FF\">您的答案:</font>%@     </a><img src=\"table_no.png\" width=\"18\"></p><p><a><font color=\"#0000FF\">知识点:</font>%@</a></p><p><a><font color=\"#0000FF\">正确答案:</font>%@</a></p><a><font color=\"#0000FF\">试题分析:</font> %@</a>",selectionStr,[dataDict objectForKey:@"categoryName"],[dataDict objectForKey:@"answer"],[dataDict objectForKey:@"analysis"]];
//    CGSize anyliseSize = [anyliseHTMLData sizeWithFont:[UIFont systemFontOfSize:15.0] constrainedToSize:CGSizeMake(300, 1000)];
//    UILabel *lineLabel = (UILabel *)[self viewWithTag:1000];
//    [lineLabel setHidden:NO];
//    
//    UIWebView *webView = (UIWebView *)[self viewWithTag:1001];
//    [webView setHidden:NO];
//    [webView loadHTMLString:anyliseHTMLData baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
//
//    [self setContentSize:CGSizeMake(300,h+([optionsArray count]+1)*43+anyliseSize.height+1+40)];
//    if (webView) {
//        [webView loadHTMLString:<#(NSString *)#> baseURL:<#(NSURL *)#>]
//    }
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}
- (id)initWithFrame:(CGRect)frame  isSingle:(BOOL)isSingle isShowAnswer:(BOOL)isShowAnswer  anlysise:(BOOL )anlysise dataDict:(NSMutableDictionary *)dataDict_;
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        NSString *orderIdStr =[dataDict_ objectForKey:@"orderid"];
        NSString *titleStr =[dataDict_ objectForKey:@"questionContent"];
        NSString *str = [NSString stringWithFormat:@"%@.%@",orderIdStr,titleStr];
        CGSize size_0 = CGSizeMake(FMSCREENWIDTH-20, 1000);
        CGSize size = [str sizeWithFont:[UIFont systemFontOfSize:16.0]constrainedToSize:size_0 lineBreakMode:NSLineBreakByWordWrapping];
        int x,y,w,h;
        x = 10;y=2;w=FMSCREENWIDTH-20;h = size.height+30;
        UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, FMSCREENWIDTH-20, h)];
//        UIImage *bgImage = [[ApplicationInfo getImageFromLocalFile:@"bgImage"] stretchableImageWithLeftCapWidth:10 topCapHeight:10];
//        [bgImageView setImage:bgImage];
//        [bgImageView setBackgroundColor:[UIColor colorWithRed:213/255.0 green:222/255.0 blue:235/255.0 alpha:11.0]];
//        bgImageView.layer.cornerRadius = 2.0;
//        bgImageView.layer.borderWidth = 1.0;
//        bgImageView.layer.borderColor = [UIColor colorWithRed:213/255.0 green:222/255.0 blue:235/255.0 alpha:11.0].CGColor;
        [bgImageView setTag:499];
        [self addSubview:bgImageView];
        
        UIImageView *lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, y+h, 280, 2)];
        [lineImageView setImage:[ApplicationUtils getLocalImage:@"st_line@2x"]];
        [lineImageView setTag:501];
        [self addSubview:lineImageView];
        
        UIWebView *selectionView = [[UIWebView alloc] initWithFrame:CGRectMake(x,y,w,h)];
        [selectionView setBackgroundColor:[UIColor clearColor]];
        [selectionView setTag:500];
        [selectionView setOpaque:NO];
        [selectionView setDelegate:self];
        NSString *HTMLData = str;
        NSString *path = [FMPAPERSAVE_PATH stringByAppendingPathComponent:@"image"];
        
        [selectionView loadHTMLString:HTMLData baseURL:[NSURL fileURLWithPath:path]];
        [bgImageView addSubview:selectionView];
        x=6;
        y=y+h;
        NSArray  *optionsArray = [dataDict_ objectForKey:@"options"];
        for (int i=0; i<[optionsArray count]; i++) {
            @autoreleasepool {
            XingAndLabel_UIView* labelBtn=[[XingAndLabel_UIView alloc] initWithFrame:CGRectMake(x, y+45*i, w-5, 45)isNecessary:isSingle withTitleStr:[optionsArray objectAtIndex:i] with_FontOfSize:15.0];
            ISMutileButton *selectBtn = (ISMutileButton *)[labelBtn viewWithTag:88];
            [selectBtn addTarget:self action:@selector(selectBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
            [labelBtn setDelegate:self];
            if (i == 0) {
                self.selectedBtn = selectBtn;
            }
            ISMutileButton *choseBtn = (ISMutileButton *)[labelBtn viewWithTag:89];
            [choseBtn addTarget:self action:@selector(choseBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
//            [labelBtn setTag:500];
            [self addSubview:labelBtn];
            if (isShowAnswer) {
                NSString *answer = [dataDict_ objectForKey:@"answer"];
                if ([answer rangeOfString:@"A"].location != NSNotFound&&i==0) {
                    [selectBtn setSelected:YES];
                }else if ([answer rangeOfString:@"B"].location != NSNotFound&&i==1){
                    [selectBtn setSelected:YES];
                }else if ([answer rangeOfString:@"C"].location != NSNotFound&&i==2){
                    [selectBtn setSelected:YES];
                }else if ([answer rangeOfString:@"D"].location != NSNotFound&&i==3){
                    [selectBtn setSelected:YES];
                }else if ([answer rangeOfString:@"E"].location != NSNotFound&&i==4){
                    [selectBtn setSelected:YES];
                }else if ([answer rangeOfString:@"F"].location != NSNotFound&&i==5){
                    [selectBtn setSelected:YES];
                }
                [selectBtn setUserInteractionEnabled:NO];
                [choseBtn setUserInteractionEnabled:NO];
            }else{
                [selectBtn setSelected:NO];
                [selectBtn setUserInteractionEnabled:YES];
                [choseBtn setUserInteractionEnabled:YES];
            }
            if (anlysise) {
                NSString *answer = [dataDict_ objectForKey:@"user_answer"];
                if (isSingle == NO) {
                    FMSCHBLog(@"------->cui----->%@",answer);
                }
                FMSCHBLog(@"user_answer:%@",answer);
                if (answer!=nil&&[answer rangeOfString:@"A"].location != NSNotFound&&i==0) {
                    [selectBtn setSelected:YES];
                }else if (answer!=nil&&[answer rangeOfString:@"B"].location != NSNotFound&&i==1){
                    [selectBtn setSelected:YES];
                }else if (answer!=nil&&[answer rangeOfString:@"C"].location != NSNotFound&&i==2){
                    [selectBtn setSelected:YES];
                }else if (answer!=nil&&[answer rangeOfString:@"D"].location != NSNotFound&&i==3){
                    [selectBtn setSelected:YES];
                }else if (answer!=nil&&[answer rangeOfString:@"E"].location != NSNotFound&&i==4){
                    [selectBtn setSelected:YES];
                }else if (answer!=nil&&[answer rangeOfString:@"F"].location != NSNotFound&&i==5){
                    [selectBtn setSelected:YES];
                }
                if (answer!=nil&&[answer rangeOfString:@"正确"].location != NSNotFound&&i==0) {
                    [selectBtn setSelected:YES];
                }else if (answer!=nil&&[answer rangeOfString:@"错误"].location != NSNotFound&&i==1){
                    [selectBtn setSelected:YES];
                }
                [selectBtn setUserInteractionEnabled:YES];
                [choseBtn setUserInteractionEnabled:YES];
            }
        }
        }
        y =  y+43+43*[optionsArray count];
        UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, y, 280, 1)];
        [lineLabel setBackgroundColor:[UIColor lightGrayColor]];
        [lineLabel  setTag:1000];
        if (isShowAnswer) {
            [lineLabel setHidden:NO];
        }else{
            [lineLabel setHidden:YES];
            [self setContentSize:CGSizeMake(FMSCREENWIDTH-20,h+[optionsArray count]*43)];
        }
        _isShowAnswer = isShowAnswer;
        [self addSubview:lineLabel];
        x = x+5;
        y = y+1+5;
        NSString *user_answer = [dataDict_ objectForKey:@"user_answer"];
        NSString *answer = [dataDict_ objectForKey:@"answer"];
        NSRange range;
        if (answer.length>7) {
            range.location =3;
            range.length =answer.length-7;
        }else{
            range.location =0;
            range.length =answer.length;
        }
        answer = [answer substringWithRange:range];
        
        NSString *imageStr = @"st_Options_mark_002@2x.png";
        if ([user_answer isEqualToString:answer]) {
            imageStr = @"st_Options_mark_002@2x.png";
        }else{
            imageStr = @"st_Options_mark_001@2x.png";
            if ([user_answer isEqualToString:@""]||[user_answer isEqualToString:@"(null)"]) {
                user_answer = @"您没有选择答案";
            }
        }   
        NSString *anyliseHTMLData = [NSString stringWithFormat:@"<p><a><font color=\"#0000FF\">您的答案:</font>%@     </a><img src=\"%@\" width=\"18\"></p><p><a><font color=\"#0000FF\">知识点:</font>%@</a></p><p><a><font color=\"#0000FF\">正确答案:</font>%@</a></p><a><font color=\"#0000FF\">试题分析:</font> %@</a>",user_answer,imageStr,[dataDict_ objectForKey:@"category_name"],[dataDict_ objectForKey:@"answer"],[dataDict_ objectForKey:@"analysis"]];
        CGSize anyliseSize = [anyliseHTMLData sizeWithFont:[UIFont systemFontOfSize:15.0] constrainedToSize:CGSizeMake(FMSCREENWIDTH-20, 1000)];
        x = x-5;
        y = y;
        UIWebView *anylisewebView = [[UIWebView alloc] initWithFrame:CGRectMake(x,y,anyliseSize.width,anyliseSize.height+40)];
        [anylisewebView setBackgroundColor:[UIColor clearColor]];
        [anylisewebView setTag:1001];
        if (isShowAnswer) {
            [anylisewebView setHidden:NO];
            [self setContentSize:CGSizeMake(FMSCREENWIDTH-20,h+[optionsArray count]*43+anyliseSize.height+40)];
        }else{
            [anylisewebView setHidden:YES];
        }
        [anylisewebView setUserInteractionEnabled:NO];
        [anylisewebView setOpaque:NO];
        [anylisewebView setDelegate:self];
        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"st_Options_mark_001@2x" ofType:@"png"]];
        [anylisewebView loadHTMLString:anyliseHTMLData baseURL:url];
        [self addSubview:anylisewebView];
        
//        [self hideToastActivity];
//        [self setContentSize:CGSizeMake(300,h+([optionsArray count]+1)*43+anyliseSize.height+1+40)];

//        x=6;
//        y=h+[optionsArray count]*43;
//        webView = [[UIWebView alloc] initWithFrame:CGRectMake(x,y,w,h)];
//        [webView setBackgroundColor:[UIColor clearColor]];
//        [webView setOpaque:NO];
//        [webView setHidden:YES];
//        [webView setDelegate:self];
//        [self addSubview:webView];
    }
    return self;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // finished loading, hide the activity indicator in the status bar
//    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'"];
//    [self hideToastActivity];
    UIWebView *webView_ = (UIWebView *)[self viewWithTag:500];
    if (webView_) {
        [webView_ setFrame:CGRectMake(webView_.frame.origin.x, webView_.frame.origin.y, webView_.frame.size.width, webView_.scrollView.contentSize.height)];
    }
    UIImageView *imageView = (UIImageView *)[self viewWithTag:499];
    if (imageView) {
        [imageView setFrame:CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y, imageView.frame.size.width, webView_.scrollView.contentSize.height)];
    }
    UIImageView *lineImageView = (UIImageView *)[self viewWithTag:501];
    if (lineImageView) {
        [lineImageView setFrame:CGRectMake(imageView.frame.origin.x+10, imageView.frame.origin.y+webView_.scrollView.contentSize.height, imageView.frame.size.width-20, 2)];
    }
    int y = imageView.frame.origin.y+imageView.frame.size.height+10;
    int height = 0;
    int i=0;
    for (UIView *subView in  [self subviews]) {
        if (subView!=nil&&[subView isKindOfClass:[XingAndLabel_UIView class]]) {//仔XingAndLabel_UIView中已经设置了宽度位webView的宽度，此时只改变y
            [subView setFrame:CGRectMake(subView.frame.origin.x, y+height, FMSCREENWIDTH-20, subView.frame.size.height)];
            height = height+subView.frame.size.height;
            i++;
            self.contentSize = CGSizeMake(FMSCREENWIDTH, subView.frame.origin.y+subView.frame.size.height);//cuichange  20141219  解决单选和多选选项太多超出屏幕不能显示全问题
        }
    }
    UILabel *lineLabel = (UILabel *)[self viewWithTag:1000];
    [lineLabel setFrame:CGRectMake(lineLabel.frame.origin.x, y+height+5,lineLabel.frame.size.width,1)];
    
    UIWebView *anlysizeWebView = (UIWebView *)[self viewWithTag:1001];
    anlysizeWebView.frame = CGRectMake(anlysizeWebView.frame.origin.x, y+height+5+1+5, anlysizeWebView.frame.size.width, anlysizeWebView.scrollView.contentSize.height);
//    if (_isShowAnswer) {
//        self.contentSize = CGSizeMake(FMSCREENWIDTH, y + height+anlysizeWebView.scrollView.contentSize.height);//(height+5+1+5)+anlysizeWebView.scrollView.contentSize.height
//    }else{
//        self.contentSize = CGSizeMake(FMSCREENWIDTH, y + height);
//    }
//    if (paperDelegate!=nil&&[paperDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
//        [paperDelegate webViewDidFinishLoad:webView];
//    }
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
        
}

-(void)dealloc{
    paperDelegate=nil;
    if (self.paperDict) {
        self.paperDict = nil;
    }
    selectedBtn = nil;
    //清除UIWebView的缓存
    [ [NSURLCache  sharedURLCache ] removeAllCachedResponses];
}
@end
